package com.qiyuesuo.client.controller;

import com.qiyuesuo.client.service.FileService;
import com.qiyuesuo.client.util.RSA.RSASignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Scanner;
import java.util.UUID;

/**
 * 模拟文件上传请求，将文件上传到服务端
 *
 * @author s77
 * @create 2020-4月-02 12:31
 */
@Controller
public class UploadController {
    private final static Logger logger = LoggerFactory.getLogger(UploadController.class);

    private static final String REQUEST_PATH = "http://localhost:8081/upload";
    private static final String METHOD = "POST";
    private static final String BOUNDARY = "------WebKitFormBoundaryKPjN0GYtWEjAni5F";//分隔符，任意但不可以和上传文件重复

    @Autowired
    @Qualifier("fileService")
    private FileService fileService;

    @RequestMapping("/upload")
    @ResponseBody
    public String uploadFile(HttpServletRequest request,
                             @RequestParam("file") MultipartFile file) throws IllegalStateException, IOException {
        HttpURLConnection httpConn = fileService.gethttpConn(REQUEST_PATH, METHOD);
        httpConn.setRequestProperty("Content-Type", "multipart/form-data;charset=gbk; boundary=" + BOUNDARY);
        OutputStream os = httpConn.getOutputStream();
        BufferedOutputStream bos = new BufferedOutputStream(os);

        String content = "--" + BOUNDARY + "\r\n";
        content += "Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getOriginalFilename() + "\"\r\n";
        content += "Content-Type: " + file.getContentType() + "\r\n\r\n";
        bos.write(content.getBytes());

        // 开始写出文件的二进制数据
        InputStream fin = file.getInputStream();
        BufferedInputStream bfi = new BufferedInputStream(fin);
        byte[] buffer = new byte[4096];
        int bytes = bfi.read(buffer, 0, buffer.length);
        while (bytes != -1) {
            bos.write(buffer, 0, bytes);
            bytes = bfi.read(buffer, 0, buffer.length);
        }
        bfi.close();
        fin.close();
        bos.write(("\r\n--" + BOUNDARY).getBytes());
        bos.flush();
        bos.close();
        os.close();

        // 读取返回数据
        StringBuffer strBuf = new StringBuffer();
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                httpConn.getInputStream()));
        String line = null;
        while ((line = reader.readLine()) != null) {
            strBuf.append(line).append("\n");
        }
        String res = strBuf.toString();
        reader.close();
        httpConn.disconnect();
        return res;
    }

}
